<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Comcheck;
use App\Model\Area;

class WordController extends Controller
{
    /*word文档管理*/
    public function index(Request $request)
    {
    	/*获取文档列表*/
    	$name = $request->input("name","");
        $community_id = $request->input("community",0);

        /*获取社区*/
        $street = Area::where('name', '北宅街道')->first();
        $street = json_decode(json_encode($street), true);
        $community = Area::where('pid', $street['id'])->get()->toArray();
        $all_area = array_merge(array($street),$community);
        $all_area = array_column($all_area, NULL, 'id');

		$comcheck_obj = new Comcheck();
		$list = $comcheck_obj->getCheckss($name,0,$street['id'],$community_id);
    	$list = json_decode(json_encode($list), true);
        $data = $this->listTransfer($list,$all_area);
        
    	return view('admin.word.index',[
    		'name' => $name,
            'community_id' => $community_id,
    		'data' => $data,
            'community' => $community,
            'data_length' => count($data)
    	]);
    }

    protected function listTransfer($list, $area)
    {
        $returnData = array();
        $area = array_column($area,null,'id');
        foreach ($list as $key => $value) {
            $word_arr = explode(",", $value['wordsUrl']);
            // $tmp_area = $area[$value['street']]['name'].'-'.$area[$value['community']]['name'];
            $tmp_area = $area[$value['street']]['name'];
            $tmp_arr = array();
            foreach($word_arr as $k=>$v) {
                /*处理文档名称*/
                preg_match("/^(\.\/storage\/word\/)[0-9]{8}\//i",$v, $matches);
                $front = '';
                if(!empty($matches)) {
                    $front = $matches[0];
                }
                $after = '';
                preg_match("/\_[0-9]{12}\.docx$/i", $v, $matches);
                if(!empty($matches)) {
                    $after = $matches[0];
                }
                $word_name = str_replace(array($front, $after), '', $v);
                $tmp_arr[$k]['name'] = $word_name;
                $tmp_arr[$k]['url'] = trim($v,'.');
                $tmp_arr[$k]['checkId'] = $value['checkId'];
                if(!empty($value['updated'])) {
                    $tmp_arr[$k]['create_time'] = date('Y-m-d H:i:s',$value['updated']);
                } else {
                    $tmp_arr[$k]['create_time'] = $value['created'];
                }
                $tmp_arr[$k]['area'] = $tmp_area;
            }
            $returnData = array_merge($returnData,$tmp_arr);
        }
        return $returnData;
    }

    /*批量下载*/
    public function batchDownload(Request $request)
    {
        $name= $request->input("name","");
        $community_id = $request->input("community_id",0);


        /*获取街道*/
        $street = Area::where(array('name'=>'北宅街道'))->first();
        $street = json_decode(json_encode($street), true);
        /*获取社区下的公司文档*/
        $comcheck_obj = new Comcheck();
        $list = $comcheck_obj->getCheckss($name,0,$street['id'],$community_id);
        $list = json_decode(json_encode($list), true);
        $fileArr = array();
        foreach ($list as $key => $value) {
            $word_arr = explode(",", $value['wordsUrl']);
            $tmp_arr = array();
            foreach($word_arr as $k=>$v) {
                /*处理文档名称*/
                preg_match("/^(\.\/storage\/word\/)[0-9]{8}\//i",$v, $matches);
                $front = '';
                if(!empty($matches)) {
                    $front = $matches[0];
                }
                $word_name = str_replace(array($front), '', $v);
                $tmp_arr[$k]['file_path'] = '.'.trim($v,'.');
                $tmp_arr[$k]['down_path'] = $word_name;
            }
            $fileArr = array_merge($fileArr, $tmp_arr);
        }

        $zipname = './storage/download/'.date('Ymdhis').'.zip';

        //要使用该类，需要先启用 extension=php_zip.dll
        $zip = new \ZipArchive();
        $res = $zip->open( $zipname, \ZIPARCHIVE::CREATE );

        $file_num = 0;
        if ($res === TRUE) {
            foreach ( $fileArr as $file ) {
                //这里将服务器上的文件添加到下载内容中，并重新赋值下载zip文件内该文件的路径
                if(!empty($file ['file_path'])&&!empty($file['down_path'])) {
                    $add_res = $zip->addFile( $file ['file_path'], $file ['down_path'] );
                    if($add_res === TRUE) {
                        $file_num = $file_num+1;
                    }
                } 
            }
        }

        $zip->close(); 
           
        $zip_size = 0;
        if($file_num > 0) {
            $zip_size = filesize ( $zipname );
        }

        $file = fopen($zipname,"r");
        //返回的文件类型
        Header("Content-type: application/octet-stream");
        //按照字节大小返回
        Header("Accept-Ranges: bytes");
        //返回文件的大小
        Header("Accept-Length: ".filesize($zipname));
        //这里设置客户端的弹出对话框显示的文件名
        Header("Content-Disposition: attachment; filename=".basename ( $zipname ));
        //一次只传输1024个字节的数据给客户端
        //向客户端回送数据
        $buffer=1024;//
        //判断文件是否读完
        while (!feof($file)) {
            //将文件读入内存
            $file_data = fread($file, $buffer);
            //每次向客户端回送1024个字节的数据
            echo $file_data;
        }
        fclose($file);
        //如不删除，则在服务器上会有 $zipname 这个zip文件
        @unlink ( $zipname );

    }
}
